/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2016 pjoc.pub, blademainer.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */
package pub.pjoc.exception;

import pub.pjoc.pay.vo.ReturnResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;
import org.springframework.web.servlet.view.xml.MappingJackson2XmlView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 异常统一处理类，根据前端请求的需要，返回XML|JSON|或者网页格式
 *
 * @author xiongyingqi
 */
public class InterfaceExceptionHandler extends AbstractHandlerExceptionResolver {

  private static final Logger logger = LoggerFactory
      .getLogger(InterfaceExceptionHandler.class);

  private static final String ACCEPT = "Accept";

  //异常jsp页面
  private static final String EXCEPTION_JSP_PATH = "exception";

  /*
   * (non-Javadoc)
   * @see
   * org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver#
   * doResolveException(javax.servlet.http.HttpServletRequest,
   * javax.servlet.http.HttpServletResponse, java.lang.Object,
   * java.lang.Exception)
   */
  @Override
  protected ModelAndView doResolveException(HttpServletRequest request,
                                            HttpServletResponse response, Object handler,
                                            Exception ex) {
    //根据accept返回需要的数据格式
    String accept = request.getHeader(ACCEPT);
    ReturnResult result = ReturnResult.SYSTEM_ERROR;
    if (logger.isDebugEnabled()) {
      logger.debug("get Accept:{}", accept);
    }
    logger.error("Exception occurs from " + handler, ex);
    if (MediaType.TEXT_HTML_VALUE.equals(accept)
        || MediaType.APPLICATION_XHTML_XML_VALUE.equals(accept)) { //html
      ModelAndView modelAndView = new ModelAndView(EXCEPTION_JSP_PATH);
      return modelAndView;
    }

    ModelAndView modelAndView = new ModelAndView();
    if (MediaType.APPLICATION_JSON_VALUE.equals(accept)) {//JSON
      modelAndView.setView(new MappingJackson2JsonView());
    } else {
      // 默认返回XML
      modelAndView.setView(new MappingJackson2XmlView());
    }
    modelAndView.addObject(result);
    return modelAndView;
  }

}
